import httpclient, parseopt, strformat, strutils

const
  languages = ["cs", "de", "en", "fr", "hi", "ru"]
  languagesList = languages.join("/")
  usageInformation = """
lindat [OPTIONS] [SOURCE-LANGUAGE [TARGET-LANGUAGE [FILE]]]
Use the LINDAT translation service to translate the contents of FILE or STDIN
from SOURCE-LANGUAGE to TARGET-LANGUAGE and output the translation to STDOUT.
When TARGET-LANGUAGE is unspecified, it defaults to "en".
When all arguments are unspecified, the tool interactively asks
for SOURCE-LANGUAGE, TARGET-LANGUAGE and the phrase to translate.

Options:
-h, --help
  Print this usage information to STDOUT and exit.
"""

var
  sourceLanguage: string
  targetLanguage: string = "en"
  filename: string
  phrase: string
  argumentIndex = 0

# Parse command line arguments
for kind, key, val in getopt():
  case kind
  of cmdArgument:
    case argumentIndex
    of 0:
      sourceLanguage = key
    of 1:
      targetLanguage = key
    of 2:
      filename = key
    of 3:
      stderr.writeLine "Warning: Expected three or fewer arguments"
    else: discard
    argumentIndex.inc
  of cmdShortOption:
    case key
    of "h":
      stdout.write usageInformation
      quit QuitSuccess
  of cmdLongOption:
    case key
    of "help":
      stdout.write usageInformation
      quit QuitSuccess
  else: discard

# Get source language if not given and verify validity
if argumentIndex == 0:
  stdout.write &"Source language ({languagesList}): "
  sourceLanguage = stdin.readLine
if sourceLanguage notin languages:
  stderr.writeLine &"Error: Unsupported language: {sourceLanguage}"
  stderr.writeLine &"(Supported languages: {languagesList})"
  quit QuitFailure
if sourceLanguage == "hi":
  stderr.writeLine "Error: Hindi is not supported as an input language"
  quit QuitFailure

# Get target language if not given and verify validity
if argumentIndex == 0:
  stdout.write &"Target language ({languagesList}): "
  targetLanguage = stdin.readLine
if targetLanguage notin languages:
  stderr.writeLine &"Error: Unsupported language: {targetLanguage}"
  stderr.writeLine &"(Supported languages: {languagesList})"
  quit QuitFailure

# Get phrase to translate and remove newline if present
if argumentIndex == 0:
  stdout.write "Phrase to translate: "
  phrase = stdin.readLine
elif filename != "":
  phrase = readFile(filename)
else:
  phrase = stdin.readAll
phrase.stripLineEnd

# Generate information for tho web API
let
  url = &"https://lindat.mff.cuni.cz/services/translation/api/v2/languages/?src={sourceLanguage}&tgt={targetLanguage}"
  data = newMultipartData {"input_text": phrase}
  client = newHttpClient()
client.headers = newHttpHeaders {
  "accept": "text/plain",
  "Content-Type": "application/x-www-form-urlencoded",
}

# Get the translation and print it
let translation = client.postContent(url, multipart = data)
stdout.write translation
